package com.offcn.scworder.service.impl;

import com.offcn.dycommon.enums.OrderStatusEnume;
import com.offcn.dycommon.response.AppResponse;
import com.offcn.scworder.vo.resp.TReturn;
import com.offcn.scworder.mapper.TOrderMapper;
import com.offcn.scworder.pojo.TOrder;
import com.offcn.scworder.service.OrderService;

import com.offcn.scworder.service.ProjectServiceFeignService;
import com.offcn.scworder.vo.req.OrderInfoSubmitVo;
import com.offcn.scworder.vo.resp.TReturn;
import com.offcn.utils.AppDateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TOrderMapper orderMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProjectServiceFeignService projectServiceFeign;

    @Override
    public TOrder saveOrder(OrderInfoSubmitVo vo) {
        TOrder order = new TOrder();
        BeanUtils.copyProperties(vo,order);
        String s = redisTemplate.opsForValue().get(vo.getAccessToken());
        Integer memberId = Integer.parseInt(s);
        order.setMemberid(memberId);
        //设置时间
        order.setCreatedate(AppDateUtils.getFormatTime());
        //设置订单编号
        String orderNum = UUID.randomUUID().toString().replace("-", "");
        order.setOrdernum(orderNum);
        //设置状态
        order.setStatus(OrderStatusEnume.UNPAY.getCode()+"");
        //设置发票的状态
        order.setInvoice(vo.getInvoice()+"");
        //设置订单的金额 = 支持的笔数*支持的金额+运费
        AppResponse<List<TReturn>> returnList = projectServiceFeign.getReturnList(vo.getProjectid());
        List<TReturn> data1 = returnList.getData();
        TReturn userReturn = null ;
        for (TReturn tReturn : data1) {
            if (tReturn.getId().intValue() == vo.getReturnid().intValue()) {
                userReturn = tReturn;
            }
        }
        Integer money = order.getRtncount() * userReturn.getSupportmoney() + userReturn.getFreight();
        order.setMoney(money);
        //保存数据库
        orderMapper.insert(order);
        return order;
    }
}
